<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>添加付款管理</title>
	<link rel="stylesheet" href="../css/from.css">
	<link rel="stylesheet" href="../themes/default/easyui.css">
	<link rel="stylesheet" href="../themes/icon.css">
	<script src="../js/jquery.min.js"></script>
	<script src="../js/jquery.easyui.min.js"></script>
	<script src="../js/easyui-lang-zh_CN.js"></script>
	<script>

        function addNewPayBillDetail(){
            var row={billCode: "",a: "应付帐目",b: "减少",
                payMoney:"",realMoney:"0",memo: "",operation: ""};
            $("#productList").datagrid("appendRow",row);
        }

        //添加paybill
        function addProduct() {
            parent.addTabs("添加付款单","goods/add_PayBill.html");
        }

        //支付方法
        function payCurrentPayBill(){
            $.messager.confirm('确认','您确认想要审核吗？',function(r){
                if (r){
                    if ($("#addDate").datebox('isValid')){
                        $.ajax({
                            url: "../../payBillController/savePayBillDetailToDataBase",
                            data: {saveRows: JSON.stringify($("#productList").datagrid("getRows")),
                                payCode: $("#code").val(),
                                payData: $("#addDate").datebox("getText"),
                                payType: $("#contacter").combobox("getValue"),
                                payTotalMoney: $("#type").textbox('getValue'),
                                memo: $("#fax").textbox("getText")},
                            dataType: "text",
                            success: function(data){
                            	if(data.result=='noPower'){
                            		alert("没有权限");
                            	}else{
                            		$("#addDate").datebox('setValue','yyyy-mm-dd');
                                $.ajax({
                                    url: "../../payBillController/payCurrentPayBill",
                                    data: {code:$("#code").val()},
                                    beforeSend:function(){
                                        ajaxLoading();
                                        return true;
                                    },
                                    dataType:"text",
                                    success:function(data){
                                        alert(data);
                                        $.ajax({
                                            url: "../../payBillController/findPayBill",
                                            data:{payCode:$("#code").val()}
                                        });
                                        ajaxLoadEnd();
                                        window.location.href="paybill_detail_checked.html";
                                    }
                                });
                            	}
                            },
                            error: function(){
                                return false;
                            }
                        });
                        return true;
                    }else{
                        alert("请输入正确的时间");
                        return false;
                    }
                }
            });

        }

        //保存功能
        function savePayBillDetailToDataBase(){
			if ($("#addDate").datebox('isValid')){
				$.ajax({
                    url: "../../payBillController/savePayBillDetailToDataBase",
                    data: {saveRows: JSON.stringify($("#productList").datagrid("getRows")),
                        payCode: $("#code").val(),
                        payData: $("#addDate").datebox("getText"),
                        payType: $("#contacter").combobox("getValue"),
                        payTotalMoney: $("#type").textbox('getValue'),
                        memo: $("#fax").textbox("getText")},
                    dataType: "text",
                    success: function(data){
                        if(data=="success"){
                            alert("保存成功");
                         	parent.tabsClose();
                        }else{
                        	alert(data);
                        }
                    },
                    error: function(){
                        return false;
                    }
                });
                return true;
            }else{
                alert("请输入正确的时间");
                return false;
            }
		}
        //删除instroagebill的一行数据，删除后重置datagrid
        function deleteInstroageBillInRow(index){
            var rows=$("#productList").datagrid('getRows');
            var a=parseFloat($("#type").textbox('getValue'));
            var b=rows[index].payMoney;
            if (b!=null ||b!=undefined ||b!=""){
                var curMoney=a-b;
                $("#type").textbox('setValue',curMoney);
                $("#productList").datagrid('deleteRow',index);
                rows=$("#productList").datagrid('getRows');
                $("#productList").datagrid('loadData',rows);
            }
        }


        //从未选择的introagebill选择一个添加
        function addInstroageBillTopaybill(){
            var selectRows=$("#instroagebill").datagrid("getSelections");
            var rows=$("#productList").datagrid("getRows");
            if(selectRows==null||selectRows==""){
                alert("请选择入库单！");
                return false;
            }
            var flag=false;
            if(rows!=null||rows!=""){
                for(var i=0;i<selectRows.length;i++){
                    for(var j=0;j<rows.length;j++){
                        if(rows[j].billCode==selectRows[i].code){
                            flag=true;
                        }
                    }
                }
                if(flag==false){
                    for(var i=0;i<selectRows.length;i++){
                        var addrow={billCode: selectRows[i].code,a: "应付帐目",b: "减少",
                            payMoney:selectRows[i].money,realMoney:0,memo: selectRows[i].memo,operation: ""};
                        $("#productList").datagrid('appendRow',addrow);
                        var curMoney=parseFloat($("#type").textbox('getValue'))+selectRows[i].money;
                        $("#type").textbox('setValue',curMoney);
                    }
                }else{
                    alert("请不要选择重复入库单！");
                    $("#instroagebill").datagrid("clearSelections");
                    $("#instroagebill").datagrid("clearChecked");
                    return false;
                }
            }else{
                for(var i=0;i<selectRows.length;i++){
                    var addrow={billCode: selectRows[i].code,a: "应付帐目",b: "减少",
                        payMoney:selectRows[i].money,realMoney:0,memo: selectRows[i].memo,operation: ""};
                    $("#productList").datagrid('appendRow',addrow);
                    var curMoney=parseFloat($("#type").textbox('getValue'))+selectRows[i].money;
                    $("#type").textbox('setValue',curMoney);
                }
            }
            $("#win").window('close');
        }

        //加载paybill的入库单
        function searchInstroageBill(){
            var json = {
                findcode: $("#findcode_I").val(),
                findstartDate: $("#findstartDate_I").val(),
                findendDate: $("#findendDate_I").val(),
                findsupplierName: $("#findsupplierName_I").val(),
                payCode: $("#code").val()
            };
            loadInstroageListByPayBill(json);

        }

        //加载paybill的instroagebill 的datagrid方法
        function loadInstroageListByPayBill(params){
            $("#instroagebill").datagrid({
                fit: true,
                url:'../../payBillController/loadUnselectedInstroageBill',
                toolbar:'#instroageToolbar',
                rownumbers:true,
                checkOnSelect:true,
                columns:[[
                    {field: "ck",checkbox:true},
                    {field:'code',title:'入库单号'},
                    {field: "customName",title: "供应商名"},
                    {field: "instroageDate",title: "入库日期",formatter: function (value,row,index) {
                            var date=new Date(value).toLocaleDateString().replace(/\//g,'-');
                            return date;
                        }},
                    {field:'money',title:'应付金额'},
                    {field:'payStatus',title:'实付金额',formatter:function(value,row,index){
                            if(value==1){
                                return "0.00";
                            }else if(value==2){
                                return row.money;
                            }
                        }},
                    {field:'memo',title:'备注'}
                ]],
                pagination: true,//向后台传递参数page 和rows
                pageNumber: 1,
                pageSize: 5,
                pageList: [5,10,20],
                queryParams: params

            });
        }

        //重置instroagebill面板的查找表单
        function resetForm(){
            $("#form2").form('reset');
            $("#form2").form('load',{
                findsupplierName_I: $("#supplierName").val()
            });
        }

        //从面板添加一个未选择的instroagebill到paybill的instroagebill
        function addNewInstroageBill(){
            $("#win").window('open');
            $("#form2").form('load',{
                findsupplierName_I: $("#supplierName").val()
            });
            $("#findsupplierName_I").textbox({readonly: true});
            loadInstroageListByPayBill({findsupplierName: $("#supplierName").val(),payCode: $("#code").val()});
        }

        //关闭当前这个页面
        function closeTab(){
            parent.tabsClose();
        }

        //ajax加载时提示框方法
        function ajaxLoading(){
            $("<div class=\"datagrid-mask\"></div>").css({display:"block",width:"100%",height:$(window).height()}).appendTo("body");
            $("<div class=\"datagrid-mask-msg\"></div>").html("正在处理，请稍候。。。").appendTo("body").css({display:"block",left:($(document.body).outerWidth(true) - 190) / 2,top:($(window).height() - 45) / 2});
        }
        function ajaxLoadEnd(){
            $(".datagrid-mask").remove();
            $(".datagrid-mask-msg").remove();
        }

        //撤销方法
        function revokePayBill() {
            $.ajax({
                url: "../../payBillController/revokePayBill",
                data: {code:$("#code").val()},
                beforeSend:function(){
                    ajaxLoading();
                    return true;
                },
                dataType:"text",
                success:function(data){
                	if(data.result=='noPower'){
                		alert("没有权限！");
                		ajaxLoadEnd();
                	}else{
                		$.ajax({
                        	url: "../../payBillController/findPayBill",
                        	data:{payCode:$("#code").val()}
                    	});
                    	ajaxLoadEnd();
                    	window.location.href="paybill_detail.html";
                	}
                }
            });
        }

        $(function(){
            /*设置日期验证器*/
            $.extend($.fn.validatebox.defaults.rules, {
                end: {
                    validator: function (value, param) {
                        var curDate=new Date();
                        var startTmp=new Date(curDate.toLocaleDateString());
                        var endTmp = new Date(value.replace(/-/g, "/"));
                        return startTmp <= endTmp;
                    },
                    message: '日期不能选择当前日期（今日）之前'
                }
            });

            $.extend($.fn.datagrid.defaults.editors, {
                numberbox: {
                    init: function(container, options){
                        var input = $('<input type="number" class="datagrid-editable-input">').appendTo(container);
                        return input;
                    },
                    getValue: function(target){
                        return $(target).val();
                    },
                    setValue: function(target, value){
                        $(target).val(value);
                    },
                    resize: function(target, width){
                        var input = $(target);
                        if ($.boxModel == true){
                            input.width(width - (input.outerWidth() - input.width()));
                        } else {
                            input.width(width);
                        }
                    }
                }
            });

            $.extend($.fn.datagrid.defaults.editors, {
                text: {
                    init: function(container, options){
                        var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);
                        return input;
                    },
                    getValue: function(target){
                        return $(target).val();
                    },
                    setValue: function(target, value){
                        $(target).val(value);
                    },
                    resize: function(target, width){
                        var input = $(target);
                        if ($.boxModel == true){
                            input.width(width - (input.outerWidth() - input.width()));
                        } else {
                            input.width(width);
                        }
                    }
                }
            });

            $.extend($.fn.datagrid.methods, {
                editCell: function(jq,param){
                    return jq.each(function(){
                        var opts = $(this).datagrid('options');
                        var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
                        for(var i=0; i<fields.length; i++){
                            var col = $(this).datagrid('getColumnOption', fields[i]);
                            col.editor1 = col.editor;
                            if (fields[i] != param.field){
                                col.editor = null;
                            }
                        }
                        $(this).datagrid('beginEdit', param.index);
                        for(var i=0; i<fields.length; i++){
                            var col = $(this).datagrid('getColumnOption', fields[i]);
                            col.editor = col.editor1;
                        }
                    });
                }
            });

            /* 初始化表单paybill */
            $('#form1').form('load','../../payBillController/loadPayBill');

            $("#code").textbox('readonly',true);
            $("#code").textbox('textbox').css('background','#CCCCCC');
            $("#supplierName").textbox("readonly",true);
            $("#supplierName").textbox('textbox').css('background','#CCCCCC');
            $("#type").textbox("readonly",true);
            $("#type").textbox('textbox').css('background','#CCCCCC');
            $("#contacter").combobox({editable:false});
            /* 初始化数据表格 */
            $("#productList").datagrid({
                fit:true,
                url:'../../payBillController/loadInstroageListByPayBill',
                /* rownumbers:true, */
                checkOnSelect:false,
                singleSelect: true,
                rownumbers: true,
                toolbar: '#form_field',
                onSelect:function(rowIndex, rowData){  //用于解决点击某行不会高亮
                    $('#productList').datagrid('unselectRow',rowIndex);
                },
                columns:[[
                    {field:'billCode',title:'业务单号',width: 122},
                    {field: "a",title: "本方账目",width: 100,formatter: function (value,row,index) {
                            return "应付帐目";
                        }},
                    {field: "b",title: "本方增减",width: 100,formatter: function (value,row,index) {
                            return "减少";
                        }},
                    {field:'payMoney',title:'应付金额',width: 100,formatter: function (value,row,index) {
                            return value;
                        },editor: 'numberbox'},
                    {field:'realMoney',title:'实付金额',width: 100},
                    {field:'memo',title:'备注',editor: 'text',width: 100,editor: 'text'},
                    {field: "operation",title: "操作",width: 100,formatter:function(value,row,index){
                            return "<a id='a_id_"+index+"' href='#' onclick='deleteInstroageBillInRow("+index+")'>删除</a>";
                        }}
                ]],
                pagination: false,
                onClickCell: function(index, field, value){
                    console.log(value);
                    var rows=$('#productList').datagrid('getRows');
                    var billcode=rows[index].billCode;
                    if (billcode==null ||billcode==""){
                        //减去要编辑的数量
                        if (field =='payMoney') {
                            //写入payMoney
                            if (value!=''){
                                var curMoney=parseFloat($("#type").textbox('getValue'))-parseFloat(value);
                                $("#type").textbox('setValue',curMoney);
                            }
                        }
                        $("#productList").datagrid('selectRow',index).datagrid('editCell',{index: index,field: field});
                        var editor = $('#productList').datagrid('getEditor', {index:index,field: field});
                        editor.target.focus();
                        editor.target.bind('blur', function () {
                            if (field =='payMoney') {
                                var value_e=editor.target.val();
                                if (value_e!=''){
                                    var curMoney1=parseFloat($("#type").textbox('getValue'))+parseFloat(value_e);
                                    $("#type").textbox('setValue',curMoney1);
                                }
                            }

                            //写入payMoney
                            $('#productList').datagrid('endEdit', index);
                        });
                    }else{
                        if (field =='memo') {
                            $("#productList").datagrid('selectRow',index).datagrid('editCell',{index: index,field: field});
                            var editor = $('#productList').datagrid('getEditor', {index:index,field: field});
                            editor.target.focus();
                            editor.target.bind('blur', function () {
                                $('#productList').datagrid('endEdit', index);
                            });
                        }
					}
                }/* ,//向后台传递参数page 和rows
                pageNumber: 1,
                pageSize: 5,
                pageList: [5,10,20] *//* ,
        onClickRow: function(index, row){
        	$("#productList").datagrid('beginEdit',index);
            } */
            });
            $("#win").window({
                onResize: function(width, height){
                    $("#instroageField").height(($("#win").height()-30));
                },
                onBeforeOpen:function(){
                    $("#instroageField").height(($("#win").height()-30));
                },
                onBeforeOpen:function(){
                    $("#form2").form('reset');
                    loadInstroageListByPayBill(null);
                }
            });
            /* 关闭选择入库单弹窗 */
            $("#win").window('close');
            /* 入库单弹窗textbox */
            $("#findcode_I").textbox({
                width: '100px'
            });
            $("#findsupplierName_I").textbox({
                width: '200px'
            });
            $("#findstartDate_I").datebox({
                width: '120px'
            });
            $("#findendDate_I").datebox({
                width: '120px'
            });
            //

        })
	</script>
	<style>
		body {
			font-size:12px;
			padding:10px
		}
		.l-table-edit {
			border-collapse:collapse;
			border-spacing:0;
		}
		.l-table-edit-td {
			padding:4px;
			font-size:12px;
			border:1px solid #84a0c4
		}
	</style>


</head>
<body>
<div id="form_field" style="background-color: white;">
	<form name="form1" id="form1" action="" method="post">
		<table cellpadding="0" cellspacing="0" class="l-table-edit" border="1"
			   style="width: 100%">
			<tr>
				<td width="17%" align="right" class="l-table-edit-td">产品编号：</td>
				<td width="27%" align="left" class="l-table-edit-td"><input style="height:20px"
						class="easyui-textbox" name="code" type="text" id="code" size="30"
						maxlength="100" ltype="text" /></td>
				<td width="13%" align="right" class="l-table-edit-td">付款日期：</td>
				<td width="43%" align="left" class="l-table-edit-td"><input style="height:20px"
						class="easyui-datebox" type="text" id="addDate" name="payDate"
						validType="end"/></td>
			</tr>
			<tr>
				<td width="17%" align="right" class="l-table-edit-td"><a
						href="#" onclick="loadSupplier()">供应商：</a></td>
				<td align="left" class="l-table-edit-td"><input style="height:20px"
						class="easyui-textbox" type="text" id="supplierName" value=""
						size="30" maxlength="100" ltype="text" name="customName" />
				<td width="13%" align="right" class="l-table-edit-td">付款方式：</td>
				<td align="left" class="l-table-edit-td"><select
						class="easyui-combobox" name="type" id="contacter"
						style="width: 160px ;height:20px">
					<option value="1">现金</option>
					<option value="2">转账</option>
				</select></td>
			</tr>
			<tr>
				<td width="17%" align="right" class="l-table-edit-td">付款金额：</td>
				<td align="left" class="l-table-edit-td"><input
						class="easyui-textbox" type="text" id="type" value="" size="30"
						maxlength="50" ltype="text" name="payTotalMoney"  style="height:20px"/></td>
				<td width="17%" align="right" class="l-table-edit-td">备注：</td>
				<td align="left" class="l-table-edit-td"><input type="text" style="height:20px"
																class="easyui-textbox" id="fax" value="" maxlength="50"
																ltype="text" name="memo" /></td>
			</tr>

		</table>
	</form>
	<br> <input type="button" value="新   增" style="cursor:pointer;width: 60px" onclick="addProduct()">&ensp;
	<input type="button" value="选入库单" style="cursor:pointer;width: 60px"
		   onclick="addNewInstroageBill()">&ensp;
	<input type="button" value="新增应付" style="cursor:pointer;width: 60px"
		   onclick="addNewPayBillDetail()">
	<input type="button" value="保      存" style="cursor:pointer;width: 60px"
		   onclick="savePayBillDetailToDataBase()">&ensp;
	<input
		type="button" value="审      核" style="cursor:pointer;width: 60px"
		onclick="payCurrentPayBill()">&ensp;
	<input type="button"
		   disabled="disabled" value="撤销审核" style="width: 60px">

	<input type="button" value="打     印" style="cursor:pointer;width: 60px" disabled="disabled">&ensp;
	<input type="button" value="关     闭" style="cursor:pointer;width: 60px"
		   onclick="closeTab()">&ensp;
	<div style="display: block; height: 14px"></div>
</div>
<div id="productList" class="easyui-datagrid"></div>
<div id="win" class="easyui-window easyui-layout" title="请选择 入库单"
	 style="width: 990px; height: 330px"
	 data-options="iconCls:'icon-save',modal:true">

	<div id="instroageField">
		<div id="instroageToolbar">
			<form name="form2" id="form2">
				<table width="100%" border="0" cellspacing="0"
					   style="background-color: #c9dfff;">
					<tbody>
					<tr>
						<td width="70"><b>检索条件:</b></td>
						<td width="70" align="right">入库单号:</td>
						<td width="110" align="left"><input name="findcode"
															class="easyui-textbox" type="text" id="findcode_I"></td>
						<td width="70" align="right">开始日期:</td>
						<td width="110" align="left"><input name="findstartDate"
															type="text" id="findstartDate_I" class="easyui-datebox"></td>
						<td width="70" align="right">结束日期:</td>
						<td width="110" align="left"><input name="findendDate"
															type="text" id="findendDate_I" class="easyui-datebox"></td>
						<td width="70" align="right">供应商名:</td>
						<td width="110" align="left"><input
								name="findsupplierName_I" class="easyui-textbox" type="text"
								id="findsupplierName_I"></td>
						<td width="72"><a id="search_btn" href="#"
										  class="easyui-linkbutton" data-options="iconCls:'icon-search'"
										  onclick="searchInstroageBill()">搜索</a></td>
						<td width="72"><a id="reset_btn" href="#"
										  class="easyui-linkbutton" data-options="iconCls:'icon-refresh'"
										  onclick="javascript:resetForm()">重置</a></td>
						<td width="0"></td>
					</tr>
					</tbody>
				</table>
			</form>
		</div>
		<div id="instroagebill" class="easyui-datagrid"></div>
	</div>
	<div id="instroagebill_btn" class=""
		 style="height: 30px; width: 100%; display: table; line-height: 30px;">
		<div style="float: right; line-height: 30px;">
			<input type="button" value="退出"
				   style="float: right; display: inline-block; vertical-align: middle; margin: 4px;cursor:pointer;"
				   onclick="closeInstroageField()">&ensp;&ensp; <input
				type="button" value="添加入库单"
				style="float: right; display: inline-block; vertical-align: middle; margin: 4px;cursor:pointer;"
				onclick="addInstroageBillTopaybill()">&ensp;&ensp;
		</div>
	</div>
</div>
</body>
</html>